//
//  PictureSelectViewController.swift
//  weibo
//
//  Created by 上官风雨 on 15/11/19.
//  Copyright © 2015年 上官风雨. All rights reserved.
//

import UIKit
private let column :CGFloat = 4
private let margin : CGFloat = 10
private let reuseIdentifier = "Cell"
private let maxCount = 3
private var max = 3

class PictureSelectViewController: UICollectionViewController {
    
    lazy var imageList  = [UIImage]()
    init() {
        
        let layout = UICollectionViewFlowLayout()
        let w = (screenW - (column + 1) * margin) / column
        layout.itemSize = CGSizeMake(w, w)
        layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        
        super.init(collectionViewLayout: layout)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        self.collectionView!.registerClass(PictureSelectCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        
    }
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        let mark = (imageList.count == max) ? 0 :1
        return imageList.count + mark
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! PictureSelectCell
        
        // cell.backgroundColor = UIColor.greenColor()
        cell.pictureSelectCellDelegate = self
        
        if imageList.count == indexPath.item{
            
            cell.image = nil
            
        }else{
            
            cell.image = imageList[indexPath.item]
        }
        
        return cell
    }
}
extension PictureSelectViewController :PictureSelectCellDelegate{
    
    func addBtnDidClick() {
        print("添加图片...")
        
        let picker = UIImagePickerController()
        //  picker.allowsEditing = true
        picker.delegate = self
        
        presentViewController(picker, animated: true, completion: nil)
    }
    func deleBtnDidClick(cell:PictureSelectCell) {
        
        let indexpath = collectionView?.indexPathForCell(cell)
        
        imageList.removeAtIndex(indexpath!.item)
        
        collectionView?.reloadData()
        
        print("删除图片...")
    }
    
}
//图片选择器的代理方法
extension PictureSelectViewController : UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        print(image)
        imageList.append(image)
        
        collectionView?.reloadData()
        
        print(editingInfo)
        dismissViewControllerAnimated(true, completion: nil)
    }
    
}

//自定义cell

class PictureSelectCell : UICollectionViewCell{
    //定义代理
    weak var pictureSelectCellDelegate : PictureSelectCellDelegate?
    
    @objc func addBtnDidClick(){
        
        pictureSelectCellDelegate?.addBtnDidClick?()
    }
    @objc func deleBtnDidClick(){
        
        pictureSelectCellDelegate?.deleBtnDidClick?(self)
    }
    var image:UIImage?{
        
        didSet{
            deleBtn.hidden = (image == nil)
            
            if image != nil{
                
                addBtn.setImage(image, forState: .Normal)
            }else{
                
                addBtn.setImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }
        }
    }
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
        
        contentView.addSubview(addBtn)
        contentView.addSubview(deleBtn)
        
        addBtn.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(contentView)
        }
        
        deleBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(contentView)
        }
        
        addBtn.addTarget(self, action: "addBtnDidClick", forControlEvents: .TouchUpInside)
        deleBtn.addTarget(self, action: "deleBtnDidClick", forControlEvents: .TouchUpInside)
        
    }
    //懒加载
    private lazy var addBtn : UIButton = UIButton(title: nil, backImage: "compose_pic_add", color: nil)
    
    
    private lazy var deleBtn :UIButton = UIButton(title: nil, backImage: "compose_photo_close", color: nil)
    
}

//定义协议方法
@objc protocol PictureSelectCellDelegate : NSObjectProtocol{
    
    optional  func addBtnDidClick()
    optional  func deleBtnDidClick(cell:PictureSelectCell)
    
}
